package com.fanshuai.metrics.http;

import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.dropwizard.DropwizardExports;
import io.prometheus.client.exporter.common.TextFormat;
import io.prometheus.client.hotspot.DefaultExports;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

@RestController
public class PrometheusController {
    @Resource
    private DropwizardExports dropwizardExports;
    private CollectorRegistry dropwizardRegistry;

    private CollectorRegistry hotspotRegistry;

    @Resource
    private PrometheusMeterRegistry prometheusMeterRegistry;

    /**
     * Collector  prometheus 监控数据收集器，通过collect()收集
     * CollectorRegistry  Collector容器，可以注册Collector
     */

    @PostConstruct
    public void init() {
        dropwizardRegistry = new CollectorRegistry(true);
        dropwizardRegistry.register(dropwizardExports);

        hotspotRegistry = new CollectorRegistry(true);
        DefaultExports.register(hotspotRegistry);

        /**
         * 默认使用CollectorRegistry 注册
         */
        //DefaultExports.initialize();
    }


    @RequestMapping(value = "/prometheus")
    public void prometheus(int type, HttpServletResponse response) throws Exception {
        Enumeration<Collector.MetricFamilySamples> enumeration = new Vector<Collector.MetricFamilySamples>().elements();

        switch (type) {
            case 1:
                //metrics输出到prometheus
                enumeration = dropwizardRegistry.metricFamilySamples();
                break;
            case 2:
                //prometheus client hotspot 输出到prometheus
                enumeration = hotspotRegistry.metricFamilySamples();
                break;
            case 3:
                //micrometer 输出到prometheus
                enumeration = prometheusMeterRegistry.getPrometheusRegistry().metricFamilySamples();
                break;
            default:
        }

        TextFormat.write004(response.getWriter(), enumeration);
    }

    private Enumeration<Collector.MetricFamilySamples> toEnumeration(List<Collector.MetricFamilySamples> list) {
        Vector<Collector.MetricFamilySamples> vector = new Vector<>(list);
        return vector.elements();
    }
}
